package com.lagou.homework1_3;

public class ArrayUtil {

    public static void main(String[] args) {
        //测试int类型数组arr为null时
        int[] arr = null;
        String str = ArrayUtil.toString(arr);
        System.out.println("如果int类型数组arr为null，toString方法返回字符串:" + str);
        System.out.println("--------------------------------");

        //int类型数组arr长度为0时
        int[] arr2 = {};
        str = ArrayUtil.toString(arr2);
        System.out.println("如果int类型数组arr长度为0，toString方法返回字符串:" + str);

        //测试int类型数组arr的内容为{1,2,3,4,5}时
        System.out.println("--------------------------------");
        int[] arr3 = {1, 2, 3, 4, 5};
        str = ArrayUtil.toString(arr3);
        System.out.println("如果int类型数组arr的内容为{1,2,3,4,5},toString方法返回字符串:" + str);
    }

    public static String toString(int[] arr) {
        StringBuilder sb = new StringBuilder();
        if (arr == null) {
            sb.append("null");
        } else if (arr.length == 0) {
            sb.append("[]");
        } else {
            sb.append("[");
            for (int i = 0; i < arr.length; i++) {
                if (i == arr.length-1) {
                    sb.append(arr[i]).append("]");
                } else {
                    sb.append(arr[i]).append(",").append(" ");
                }
            }
        }
        return sb.toString();
    }
}
